<!-- 退款记录 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
      <el-form-item label="申请人" prop="fullName">
        <el-input v-model="queryParams.fullName" placeholder="请输入申请人姓名" clearable size="small"
          @keyup.enter.native="handleQuery" maxlength="20" show-word-limitlength="20" show-word-limit />
      </el-form-item>
    <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入电话号码" clearable size="small"
          @keyup.enter.native="handleQuery" maxlength="11" show-word-limit />
      </el-form-item>
     
      <el-form-item label="申请时间">
        <el-date-picker v-model="dateRange" size="small" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleQuery" />
      </el-form-item>
      <el-form-item label="付款时间">
        <el-date-picker v-model="payDateRange" size="small" type="daterange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable size="small" @change="handleQuery">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['yongcanjiaofei:tuikuanjilu:export']">导出</el-button>
      </el-col>
    </el-row> -->

    <el-table v-loading="loading" :data="recordList">
      <el-table-column label="序号" align="center" type="index" width="50" />
      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column label="申请人" align="left" width="80" prop="fullName" show-overflow-tooltip />
      <el-table-column label="手机号码" align="left" prop="phone" show-overflow-tooltip />
      <el-table-column label="收款单位" align="left" prop="payee" show-overflow-tooltip />
      <el-table-column label="收款部门" align="left" prop="canteenName" show-overflow-tooltip />
      <el-table-column label="付款金额" align="center" prop="payAmount">
        <template slot-scope="scope">
          ¥{{ scope.row.totalAmount }}元
        </template>
      </el-table-column>
      <el-table-column label="付款时间" align="center" prop="payTime" width="180" show-overflow-tooltip />
      <el-table-column label="退款金额" align="center" prop="price" >
        <template slot-scope="scope">
          <span>¥{{ scope.row.price }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180" show-overflow-tooltip />
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="statusTypeMap[scope.row.status]">
            {{ statusFormat(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
          <template v-if="scope.row.status === '0'">
            <el-button size="mini" type="text" icon="el-icon-check" class="success-btn" @click="handleAudit(scope.row,1)">通过</el-button>
            <el-button size="mini" type="text" icon="el-icon-close" class="error-btn" @click="handleAudit(scope.row,2)">驳回</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 查看详情抽屉 -->
    <details-drawer ref="detailsDrawer" @refresh="getList" />

    <!-- 审核弹窗 -->
    <el-dialog :title="auditType === 1 ? '退款审核-通过' : '退款审核-驳回'" :visible.sync="auditVisible" width="500px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="80px" label-position="left" >
        <el-form-item label="申请人">
          <span>{{ auditForm.fullName }}</span>
        </el-form-item>
       
          <!-- <div class="refund-amount" v-if="auditType === 1">
            <span class="label">订单金额：</span>
            <span class="amount">¥<span class="number">{{ auditForm.totalAmount }}</span>元</span>
          </div> -->
       
        <el-form-item label="申请备注">
          <span>{{ auditForm.remark || '无' }}</span>
        </el-form-item>
        <el-form-item label="订单金额"> 
          <span style="color: #ff4949;">¥{{ auditForm.totalAmount }}元</span>
        </el-form-item>
        <el-form-item label="申请金额" :prop="auditType === 1 ? 'price' : ''">
          <template v-if="auditType === 1">
            <el-input 
              v-model="auditForm.price" 
              placeholder="请输入申请金额"
              clearable
              @input="handlePriceInput"
              @blur="handlePriceBlur"
            >
              <template slot="append">元</template>
            </el-input>
          </template>
          <template v-else>
            <span style="color: #ff4949;">¥{{ auditForm.price }}元</span>
          </template>
        </el-form-item>
        
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input v-model="auditForm.auditRemark" type="textarea" :rows="3" placeholder="请输入审核备注（100字以内）" maxlength="100" clearable show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </div>
    </el-dialog>
    
  </div>
</template>

<script>
import { listRefundRecord, auditRefund } from "@/api/yongcanjiaofei/tuikuanjilu";
import detailsDrawer from "./detailsDrawer";

export default {
  name: "",
  components: {
    detailsDrawer
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 退款记录表格数据
      recordList: [],
      // 用餐时间范围
      dateRange: [],
      // 退款时间范围
      payDateRange: [],
      // 退款状态选项
      statusOptions: [
        {
          value: "0",
          label: "待审核"
        },
        {
          value: "1",
          label: "退款成功"
        },
        {
          value: "2",
          label: "审核驳回"
        },
        {
          value: "3",
          label: "退款中"
        },
        {
          value: "4",
          label: "退款失败"
        }
      ],
      // 状态样式映射
      statusTypeMap: {
        '0': 'info',
        '1': 'success',
        '2': 'danger',
        '3': 'warning',
        '4': 'danger'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fullName: undefined,
        phone: undefined,
        collectionUnit: undefined,
        status: undefined,
        diningStartTime: undefined,
        diningEndTime: undefined,
        payStartTime: undefined,
        payEndTime: undefined
      },
      // 审核弹窗显示状态
      auditVisible: false,
      // 审核类型（1-通过，2-驳回）
      auditType: 1,
      // 审核表单
      auditForm: {
        id: undefined,
        diner: '',
        totalAmount: 0,
        remark: '',
        auditRemark: '',
        opt: '1'
      },
      // 审核表单校验规则
      auditRules: {
        auditRemark: [
          { required: false },
          { max: 200, message: '长度不能超过100个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入申请金额', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入申请金额'));
                return;
              }
              
              const numValue = parseFloat(value);
              const maxAmount = parseFloat(this.auditForm.totalAmount);
              
              if (isNaN(numValue) || numValue <= 0) {
                callback(new Error('申请金额必须大于0'));
              } else if (numValue > maxAmount) {
                callback(new Error(`申请金额不能超过订单金额 ¥${maxAmount}元`));
              } else {
                callback();
              }
            }, 
            trigger: ['blur', 'change']
          }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询退款记录列表 */
    getList() {
      this.loading = true;
      // 处理用餐时间范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.createStartTime = this.dateRange[0];
        this.queryParams.createEndTime = this.dateRange[1];
      } else {
        this.queryParams.createStartTime = undefined;
        this.queryParams.createEndTime = undefined;
      }
      // 处理退款时间范围
      if (this.payDateRange && this.payDateRange.length === 2) {
        this.queryParams.payStartTime = this.payDateRange[0];
        this.queryParams.payEndTime = this.payDateRange[1];
      } else {
        this.queryParams.payStartTime = undefined;
        this.queryParams.payEndTime = undefined;
      }
      listRefundRecord(this.queryParams).then(response => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 退款状态字典翻译
    statusFormat(row) {
      const found = this.statusOptions.find(item => item.value === row.status);
      return found ? found.label : '';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.payDateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$refs.detailsDrawer.show(row);
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有退款记录数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return exportTuikuanjilu(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    handleAudit(row, type) {
      this.auditType = type;
      // 根据审核类型设置审核备注的校验规则
      this.$set(this.auditRules.auditRemark[0], 'required', type === 2);
      this.$set(this.auditRules.auditRemark[0], 'message', '请输入审核备注');
      this.$set(this.auditRules.auditRemark[0], 'trigger', 'blur');
      
      this.auditForm = {
        id: row.id,
        fullName: row.fullName,
        totalAmount: row.totalAmount, //当前订单可退款金额
        price: row.price, //申请退款金额
        remark: row.remark,
        auditRemark: '',
        opt: type.toString()
      };
      this.auditVisible = true;
    },
    /** 提交审核 */
    submitAudit() {
      this.$refs.auditForm.validate(valid => {
        if (valid) {
          const data = {
            id: this.auditForm.id,
            opt: this.auditForm.opt,
            price: this.auditForm.price,
            remark: this.auditForm.auditRemark
          };
          auditRefund(data).then(response => {
            this.msgSuccess(`${this.auditType === 1 ? '退款审核-通过' : '退款审核-驳回'}成功`);
            this.auditVisible = false;
            this.getList();
          });
        }
      });
    },
    handlePriceInput(value) {
      // 只允许数字和一个小数点
      let cleanValue = value.replace(/[^\d.]/g, '');
      
      // 确保只有一个小数点
      const parts = cleanValue.split('.');
      if (parts.length > 2) {
        cleanValue = parts[0] + '.' + parts.slice(1).join('');
      }
      
      // 限制小数点后最多两位
      if (parts.length === 2 && parts[1].length > 2) {
        cleanValue = parts[0] + '.' + parts[1].substring(0, 2);
      }
      
      // 防止以小数点开头
      if (cleanValue.startsWith('.')) {
        cleanValue = '0' + cleanValue;
      }
      
      this.auditForm.price = cleanValue;
    },
    handlePriceBlur() {
      if (!this.auditForm.price) return;
      
      const value = parseFloat(this.auditForm.price);
      const maxAmount = parseFloat(this.auditForm.totalAmount);
      
      // 只在数值有效且不超出范围时才格式化，否则保持用户输入
      if (!isNaN(value) && value > 0 && value <= maxAmount) {
        // 格式化为两位小数
        this.auditForm.price = value.toFixed(2);
      }
      
      // 延迟触发表单验证
      this.$nextTick(() => {
        if (this.$refs.auditForm) {
          this.$refs.auditForm.validateField('price');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.success-btn {
  color: #67C23A !important;
}

.primary-btn {
  color: #409EFF !important;
}

.error-btn {
  color: #F56C6C !important;
}

.dialog-footer {
  text-align: right;
}

.refund-amount {
  display: flex;
  align-items: center;
  margin-left: 100px;
  
  .label {
    font-size: 12px;
    color: #606266;
  }
  
  .amount {
    color: #ff4949;
    font-size: 13px;
    
    .number {
      font-size: 14px;
      font-weight: bold;
      margin: 0 2px;
    }
  }
}

// 让必填星号不占用宽度
::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  position: absolute;
  left: 12px;
}
</style> 